package service

import (
	"fmt"

	"github.com/astaxie/beego/orm"

	"mutu/misc/conf"
	"mutu/misc/log"
	"mutu/models"
)

type DownloadManager struct {
}

var (
	DownloadService = DownloadManager{}
)

func (p DownloadManager) gainDownloadUrl(matter *models.Matter) (string, error) {

	r, err := ResourceService.GetResourceByUuid(matter.PsdId)
	if err != nil {
		return "", err
	}
	return r.Link, nil
}

//兑换
func (p DownloadManager) convertMatter(userId string, matter *models.Matter) (bool, error) {
	record := &models.ConvertRecord{
		UserId:   userId,
		MatterId: matter.Uuid,
	}

	if err := models.Orm.Read(record, "UserId", "MatterId"); err == nil { //有兑换记录
		return true, nil
	} else if err != orm.ErrNoRows {
		log.Log.Error("下载素材-读取素材<%s>兑换记录出错，%s", matter.Uuid, err)
		return false, err
	}

	comment := fmt.Sprintf("兑换素材<%s:%s>", matter.Uuid, matter.Title)
	if _, err := BossService.DeductScore(matter.Score, userId, comment); err != nil {
		log.Log.Error("下载素材-素材<%s>积分兑出错，%s", matter.Uuid, err)
		return false, err
	}

	record.Const = matter.Score
	if _, err := models.Orm.Insert(record); err != nil { //保存兑换记录
		log.Log.Error("下载素材-保存素材<%s>兑换记录出错，%s", matter.Uuid, err)
		return false, err
	}
	return true, nil
}

func (p DownloadManager) GetDownloadUrl(m *models.DownloadRecord) (string, error) {
	matter, err := MatterService.GetMatterByUuid(m.MatterId)
	if err != nil {
		log.Log.Error("下载素材-读取素材<%s>信息出错，%s", m.MatterId, err)
		return "", err
	}

	defer models.Orm.Insert(m) //保存下载记录

	if matter.Flag != conf.F_Matter_PSD { //如果不是PSD， 公开下载
		m.Link = matter.Link
		return m.Link, nil
	}

	//owner
	if matter.Score == 0 || matter.UserId == m.UserId {
		if m.Link, err = p.gainDownloadUrl(matter); err != nil {
			log.Log.Error("下载素材-获取素材<%s>资源信息出错，%s", m.MatterId, err)
			return "", err
		}
		return m.Link, nil
	}

	convert, err := p.convertMatter(m.UserId, matter)
	if err != nil || !convert {
		return "", err
	}

	if m.Link, err = p.gainDownloadUrl(matter); err != nil {
		log.Log.Error("下载素材-获取素材<%s>资源信息出错，%s", m.MatterId, err)
		return "", err
	}
	return m.Link, nil
}

func (p DownloadManager) GetConvertRecords(userId string) ([]*models.Matter, error) {

	var arr []*models.Matter

	sql := fmt.Sprintf(`SELECT * FROM matter a where a.uuid in (select matter_id from convert_record b where b.user_id='%s');`, userId)
	if _, err := models.Orm.Raw(sql).QueryRows(&arr); err != nil {
		log.Log.Error("读取用户<%s>兑换记录，读取失败，%s", userId, err)
		return nil, err
	}

	return arr, nil
}
